<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .box {
            width: 200px;
            height: 200px;
            background-color: rgba(0, 0, 0, 0.5);
            position: absolute;
            left: 100px;
            top: 100px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</body>
<script>

    function DragEle(ele) {//创建一个构造函数
        this.target = ele
        this.posX = null
        this.posY = null
        this.dragStart()//在构造函数中默认调用
    }
    DragEle.prototype.dragStart = function () { this.dragDown() }
    DragEle.prototype.dragEnd = function () { this.target.onmousedown = null }
    DragEle.prototype.dragDown = function () {
        this.target.onmousedown = e => {
            this.posX = e.offsetX
            this.posY = e.offsetY
            this.dragMove()
            this.dragUp()
        }
    }
    DragEle.prototype.dragMove = function () {
        document.onmousemove = e => {
            var e = e || window.event
            var x = e.pageX - this.posX
            var y = e.pageY - this.posY
            this.target.style.left = x + "px"
            this.target.style.top = y + "px"
        }
    }
    DragEle.prototype.dragUp = function () {
        document.onmouseup = () => {
            document.onmousemove = null
            document.onmouseup = null
        }
    }


    var boxList = document.getElementsByClassName('box')
    for (var i = 0; i < boxList.length; i++) {
        var box = boxList[i]
        var obj = new DragEle(box)
    }
</script>

</html>